package pers.liyan.shi.springaop.check;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Aspect
@Component
public class DepartmentAuthorityCheckAOP {

    private static final String USERNAME_PARAM_NAME = "username";

    @Before("@annotation(checker)")
    public void checkAuthority(JoinPoint point, DepartmentAuthorityChecker checker) {
        String deptCodeParamName = checker.deptCodeParamName();
        Object[] args = point.getArgs();
        MethodSignature signature = (MethodSignature) point.getSignature();
        String[] parameterNames = signature.getParameterNames();
        String username = null;
        String deptCode = null;

        for (int i = 0; i < parameterNames.length; i++) {
            if (Objects.equals(USERNAME_PARAM_NAME, parameterNames[i])) {
                username = (String) args[i];
            } else if (Objects.equals(deptCodeParamName, parameterNames[i])) {
                deptCode = (String) args[i];
            }
        }

        if (!checkUser(username, deptCode)) {
            log.error("权限验证未通过, username: {}, 部门code: {}", username, deptCode);
            throw new RuntimeException("权限验证未通过");
        }else {
            log.error("权限验证通过, username: {}, 部门code: {}", username, deptCode);
        }

    }

    private boolean checkUser(String username, String deptCode) {

        return Objects.nonNull(deptCode) && Objects.equals(username, deptCode);

    }

}
